﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Diagnostics;
using System.Xml;
using System.IO;
using System.Net;
using System.Globalization; 
using Microsoft.Win32;

using System.Threading;

using UtilityTools;
//*using BaseModule;

using AuLacGlobalsBase;
using AulacEmsDataSource;
using AulacUIProvider;
using AulacEmsClientFormBase;
using HospitalUI.SystemForms;
using HospitalUI.ListForms;

//using HospitalUI.InvForms;

namespace AulacEmsApp
{
    public partial class MainForm : BaseForm, IFormMainApp
	{
		#region API functions

		[DllImport("user32.dll")]
		public static extern IntPtr GetMenu(IntPtr hwnd);
		[DllImport("user32.dll")]
		public static extern IntPtr GetSubMenu(IntPtr hMenu,int nPos);
		[DllImport("user32.dll")]
		public static extern IntPtr GetMenuItemID(IntPtr hMenu, int nPos);
		[DllImport("user32.dll")]
		public static extern int SetMenuItemBitmaps(IntPtr hMenu, IntPtr nPosition, int wFlags, IntPtr hBitmapUnchecked, IntPtr hBitmapChecked);
		#endregion

		public static Expire SysExpire = new Expire();
		
		public static DataSet mDataHospital = null;

		#region User's Declarations
		#region public static variables
		
        public  XmlDataDocument xmlCompanyInfo = new XmlDataDocument();
		#endregion

		private bool isLogin = false;
		private ArrayList m_listOpenWnds = new ArrayList();

		
		#endregion 

		BaseForm frmBase = null;

		
		public MainForm()
		{
			InitializeComponent();
			StatusText = getUICode(UICodes.StandardStatus);
		}
/*
		[STAThread] 
		static void Main() 
		{			
			//Process ThisProcess = Process.GetCurrentProcess();
			//Process [] allProcesses = Process.GetProcesses();
			//int count = 0;

			/*foreach(Process prc in allProcesses)
			{
				if (ThisProcess.ProcessName.Equals(prc.ProcessName))
					count++;
			}
			if (count > 1)
			{
				MessageBox.Show("The current application is running, You can not run the same application at the same time!\n(Ứng dụng đang chạy, bạn không thể chạy một lần nhiều hơn một ứng dụng này!)", " Thông báo !",MessageBoxButtons.OK, MessageBoxIcon.Error);
				Application.Exit();
			}
			else
			{
				FrmMain = new MainForm();
				Application.Run(FrmMain);
			}*/
			/*try
			{
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
				FrmMain = new MainForm();
				Application.Run(FrmMain);
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}
	*/
		
		public static MainForm FrmMain = null;

        public override void OnFormLoad()
        {
            //RunTwoProcs();
            //			InitData();
            //			initOption();
            //			initCurrency();

            //ConnectSQL();
            //InitData();

            GetRegistry();
            AccessRight = new AccessRights(this.Name, true);
            FormDlgMsg dlg = new FormDlgMsg("Hệ thống đang khởi tạo dữ liêu...");
            dlg.Show();
            changeMenuToolbar();
            dlg.Close();
            FormLogin frmLogin = new FormLogin((HospitalUI.BaseForms.MainForm)this);
            InitOption();
            frmLogin.ShowDialog();
            //pnList.BringToFront();
            mDataHospital = AulacClientGlobalMember.GlobalDatasCache.CreateDataSetCache("DataHospital");
            AulacClientGlobalMember.GlobalMember.FormMain = this;
        }

		

		#region system methods
		private bool checkSecurity()
		{
			bool canAccess = true;
			return canAccess;
		}

		public void setLoginInfo(string pUserName, string password, string loginTime, XmlDataDocument xmlDoc)
		{
            AulacClientGlobalMember.GlobalMember.UserName = pUserName;
            AulacClientGlobalMember.GlobalMember.UserPassword = password;
            AulacClientGlobalMember.GlobalMember.LoginTime = AuLacGlobalsBase.DateTimeHelper.BuildLongDateTime(loginTime, AulacClientGlobalMember.GlobalMember.CultureInfo);
            InitOption();
            InitCompany();

			setLogInOut(true);
			ShowModules(xmlDoc);
		}
		
		private void ShowModules(XmlDataDocument xmldoc)
		{
			/*for (int i=1; i< mainMenu.MenuItems.Count-1; i++)
				mainMenu.MenuItems[i].Enabled = false;
				*/
			string str = XmlProcess.GetValueVchHeader(xmldoc, tagUser.IsSystem);
			bool isAdmin = bool.Parse(isEmpty(str)? "false" : str);
			XmlElement eModuleShow = XmlProcess.GetVchLinesElm(xmldoc);
            if (isAdmin == true && eModuleShow != null)
			{
				foreach(XmlElement eLine in eModuleShow.ChildNodes)
				{
					string location = eLine.GetAttribute(tagUser.Location);
					string[] arr = location.TrimEnd(";".ToCharArray()).Split(";".ToCharArray());
					bool isAccRight = bool.Parse(eLine.GetAttribute(tagUser.IsAccRight));
					foreach(MenuItem item in mainMenu.MenuItems)
						showMenu(true, location, item);

				}
				return;
			}
            if (eModuleShow != null)
            {
                foreach (XmlElement eLine in eModuleShow)
                {
                    string location = eLine.GetAttribute(tagUser.Location);
                    string[] arr = location.TrimEnd(";".ToCharArray()).Split(";".ToCharArray());
                    bool isAccRight = bool.Parse(eLine.GetAttribute(tagUser.IsAccRight));
                    foreach (MenuItem item in mainMenu.MenuItems)
                        showMenu(isAccRight, location, item);
                }
            }
		}
		private void showMenu(bool pIsAccRight, string strMenuShow, MenuItem pMnItem)
		{
			for(int i = 0; i < pMnItem.MenuItems.Count; i++)
			{
				MenuItem ctr = pMnItem.MenuItems[i];
				if(strMenuShow.IndexOf(ctr.ToString()) >= 0)
				{
					if(pIsAccRight)
						ctr.Enabled = true;
					else
						ctr.Enabled = false;
					return;
				}
				else
					showMenu(pIsAccRight, strMenuShow, ctr);
			}
		}
		public void setPassword(string password)
		{
			AulacClientGlobalMember.GlobalMember.UserPassword = password;
		}
		public void setLogInOut(bool isLogin)
		{
			this.isLogin = isLogin;
			SetViewClick(isLogin);

			if (isLogin)
			{
				mnSys.Enabled = true;
				mnSys_Logout.Enabled = true;
				if(AccessRight.IsAdministrator == true)
					mnSys_LockSys.Enabled = true;
				mnSys_Login.Enabled = false;
				mnSystem.Enabled = true;
				mnSys_ChangePass.Enabled = true;

				/*dockExamise.Enabled = dockFee.Enabled = dockReport.Enabled = dockList.Enabled =
					dockSys.Enabled = true;
					*/
				
				for (int i=1; i< mainMenu.MenuItems.Count-1; i++)
					mainMenu.MenuItems[i].Enabled = true;
			}
			else
			{
				foreach(BaseForm frm in this.MdiChildren)
				{
					if (!frm.FormMode.Equals(FormModes.ViewMode))// && frm.GetType().Equals(typeof(BaseDataForm)))
					{
						DialogResult dlg1 = MessageBox.Show(getUICode(UICodes.CloseFormMgs), getUICode(UICodes.MgsBoxCaption), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
						if (DialogResult.Yes.Equals(dlg1))
							frm.OnSaveData();
					}
					frm.Close();
				}
			
//				dockExamise.Enabled = dockFee.Enabled = dockList.Enabled = dockReport.Enabled = dockSys.Enabled = true;

				for (int i=1; i< mainMenu.MenuItems.Count-1; i++)
					mainMenu.MenuItems[i].Enabled = false;

				mnSys.Enabled = true;
				mnSys_Logout.Enabled =mnSys_ChangePass.Enabled = false;
				mnSys_LockSys.Enabled = false;
				mnSystem.Enabled = false;
				mnSys_Login.Enabled = true;
			}
		}

		private void logout()
		{
			try
			{
				menuWindows_Click(mnWnd_CloseAll, null);
				XmlElement eData = null;
				XmlDataDocument doc = createXmlDocument(ref eData, HMConfig.UpdateAccessUser, NounTypes.HspMngt);
				XmlElement eUserAccess = XmlProcess.AddChildNode(ref doc, eData, tagUser.ACCESSUSER);

				string logOutTime = mServerDate.ToShortDateString() + " " + mServerDate.ToLongTimeString();

				XmlProcess.SetAtrb(ref eUserAccess, 
					new string[] {tagUser.UserName, tagUser.DateLogin, tagUser.DateLogout},
                    new string[] { AulacClientGlobalMember.GlobalMember.UserName, AuLacGlobalsBase.DateTimeHelper.ParseLongDate(AulacClientGlobalMember.GlobalMember.LoginTime, AulacClientGlobalMember.GlobalMember.CultureInfo), logOutTime });

				processRequest(doc);

			}
			catch
			{
			}
		}

		public void changeMenuToolbar()
		{
			mnSysDB.Visible = false;
			//btSys_NewDB.Visible = btSys_OpenDb.Visible = btSys_RestoreDb.Visible = btSys_BkpDb.Visible = false;

			SetViewClick(false);

			for (int i=1; i< mainMenu.MenuItems.Count-1; i++)
				mainMenu.MenuItems[i].Enabled = false;
		}

		#endregion

		#region public methods and properties

		public void setMenuItemImage(MenuItem mnItem, Bitmap bitmap) 
		{
			try
			{
				IntPtr intptrMenu,intptrSubMenu,intptrMenuItemID = IntPtr.Zero;
				int intRet = 0;

				intptrMenu = GetMenu(this.Handle);
				intptrSubMenu = GetSubMenu(intptrMenu, ((MenuItem)mnItem.Parent).Index);
		
				intptrMenuItemID = GetMenuItemID(intptrSubMenu, mnItem.Index);
				Color backColor = bitmap.GetPixel(1, 1);
				bitmap.MakeTransparent(Color.WhiteSmoke);
				IntPtr intp = bitmap.GetHbitmap();
				intRet = SetMenuItemBitmaps(intptrMenu, intptrMenuItemID, 0 ,intp, intp);
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message, " Thông báo !");
			}
		}

		public string StatusText
		{
			get{return stPanelStatus.Text;}
			set{stPanelStatus.Text = value;}
		}

		public void ShowForm(Type typeofForm)
		{
			//ShowForm(typeofForm, false);
            ShowForm(typeofForm, false);
		}

        public void ShowForm(Type pFormType, bool pIsShowDiaLog)
        {
            if (frmBase != null)
            {
                if (!frmBase.GetType().Equals(pFormType))
                {
                    frmBase = null;
                    foreach (BaseForm frm in this.MdiChildren)
                    {
                        if (frm.GetType().Equals(pFormType))
                        {
                            frmBase = frm;
                            frmBase.FormClosing -= new FormClosingEventHandler(frmBase_FormClosing);
                            frmBase.FormClosing += new FormClosingEventHandler(frmBase_FormClosing);
                        }
                    }
                }
            }
            if (frmBase == null || frmBase.IsDisposed)
            {
                frmBase = Activator.CreateInstance(pFormType) as BaseForm;
                frmBase.FormClosing += new FormClosingEventHandler(frmBase_FormClosing);
            }


            if (!pIsShowDiaLog)
            {

                frmBase.MdiParent = this;
                frmBase.Show();
                frmBase.Activate();
                SetListFormOpenning();
                lvWnds1.RowSelected = lvWnds1.FindIndex(1, frmBase.Name);
            }
            else
            {
                frmBase.ShowDialog(this);
            }
            if (frmBase.AccessRight.IsAccRight == false)
            {
                frmBase.Close();
            }


        }


		public TypingStyles TypingStyle
		{
			get
			{
				if (mnTelexType.Checked)
					return TypingStyles.Telex;
				else if (mnVNIType.Checked)
					return TypingStyles.VNI;
				else if (mnVIQRType.Checked)
					return TypingStyles.VIQR;
				else
					return TypingStyles.System;
			}
		}
		
        public static void SetTable(DataTable tb)
		{
			if(null == mDataHospital)
			{
				mDataHospital = new DataSet("DataHospital");
			}
			DataTable tmpTb = mDataHospital.Tables[tb.TableName];
			if(tmpTb != null)
				mDataHospital.Tables.Remove(tb.TableName);
			mDataHospital.Tables.Add(tb);
		}
		
        public static void SetMedicineItem(DataTable tb)
		{
			DataTable tmpTb = mDataHospital.Tables[tb.TableName];
			DataTable tbMdngrpView = mDataHospital.Tables[TableNames.MdnGrpLoaded];
			
			if(tmpTb == null)
			{
				tmpTb = new DataTable(tb.TableName);
				foreach(DataColumn column in tb.Columns)
					tmpTb.Columns.Add(column.ColumnName);
				mDataHospital.Tables.Add(tmpTb);

			}
			if(tbMdngrpView == null)
			{
				tbMdngrpView = new DataTable(TableNames.MdnGrpLoaded);
				tbMdngrpView.Columns.Add(tagItems.MdnGrpID);
			}
			
			foreach(DataRow row in tb.Rows)
			{
				string mdnPrkID = (string)row[tagItems.MdnPrkID];
				DataRow[] arrRow = tmpTb.Select(tagItems.MdnPrkID + " Like '" + mdnPrkID + "'");
				if(arrRow == null || arrRow.Length == 0)
				{
					tmpTb.Rows.Add(row.ItemArray);
					DataRow[] rowGrp = tbMdngrpView.Select(tagItems.MdnGrpID +  " LIKE '" + (string)row[tagItems.MdnGrpID] + "'");
					if(rowGrp == null || rowGrp.Length == 0)
						tbMdngrpView.Rows.Add(new object[]{row[tagItems.MdnGrpID]});
				}
			}
			
		}

		public static DataTable GetHospitalTable(string tbName, string Query)
		{
			DataTable tmpTb = mDataHospital.Tables[tbName];
			if(tmpTb == null) return null;
			DataRow[] arrRow = null;
			if(!Query.Equals(""))
			 arrRow = tmpTb.Select(Query, tagItems.MdnID);
			else
				arrRow = tmpTb.Select("",tagItems.MdnID);

			if(arrRow == null || arrRow.Length == 0)
				return null;
			
			DataTable tb = new DataTable(tbName);
			foreach(DataColumn cl in tmpTb.Columns)
				tb.Columns.Add(cl.ColumnName); 
			foreach(DataRow row in arrRow)
				tb.Rows.Add(row.ItemArray);
			return tb;

		}


		#endregion

		#region window listner calling methods
		protected override void OnClosing(CancelEventArgs e)
		{
			if (!isLogin)
			{
				base.OnClosing(e);
				return;
			}
			DialogResult dlg = MessageBox.Show(getUICode(UICodes.ExitAppMgs), getUICode(UICodes.MgsBoxCaption), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
			if (DialogResult.No.Equals(dlg))
				e.Cancel = true;
			if (!e.Cancel)
			{
				try
				{
					/*					XmlDataDocument doc = createXmlDocument(HMConfig.UpdateAccessUser, NounTypes.HspMngt);
										XmlElement eData = (XmlElement)doc.SelectSingleNode("/* /" + tagCtrl.DATAAREA);
										XmlElement eUserAccess = XmlProcessor.addChildNode(ref doc, eData, tagUser.ACCESSUSER);

										string logOutTime = mServerDate.ToShortDateString() + " " + mServerDate.ToLongTimeString();

										XmlProcessor.setAttributeNode(ref eUserAccess, 
											new string[] {tagUser.UserName, tagUser.DateLogin, tagUser.DateLogout}, 
											new string[] {strUserName, loginTime, logOutTime});

										URLValue = MainForm.SystemName;
										processRequest(doc.OuterXml);
					*/				}
				catch{}
			}
			base.OnClosing(e);
		}

		private void BaseMainForm_MdiChildActivate(object sender, System.EventArgs e)
		{
			try
			{
				frmBase = (BaseForm)ActiveMdiChild;

                if (isEmpty(frmBase)) return;
                frmBase.FormClosing -= new FormClosingEventHandler(frmBase_FormClosing);
                frmBase.FormClosing += new FormClosingEventHandler(frmBase_FormClosing);  
  
                if (null != frmBase && (!frmBase.SDateFormat.Equals(SDateFormat)))
				{
					SetInfoFormat();
					frmBase.OnRefresh();
				}
                lvWnds1.RowSelected = lvWnds1.FindIndex(1, frmBase.Name);
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message, " Thông báo !");
			}
		}
		 		
        private void ConnectSQL()
		{
			/*FormConnectSQL frmConn = new FormConnectSQL(this);
			if (frmConn.ShowDialog().Equals(DialogResult.OK))
				stPanelSQL.Text = "Server SQL: " + AulacClientGlobalMember.GlobalMember.SqlServerName;
            */
		}
		
		private void SetViewClick(bool isVisible)
		{
			//panelNaviView.Visible = isVisible;
			mnView_OpenWnd.Checked = isVisible;
		}
		
        private void menuView_Click(object sender, System.EventArgs e)
		{
			try
			{
				if (sender.Equals(mnView_Status))
				{
					statusBar.Visible = !statusBar.Visible;
					mnView_Status.Checked = !mnView_Status.Checked;
				}
				else if (sender.Equals(mnView_OpenWnd))
				{
					//panelNaviView.Visible = !panelNaviView.Visible;
					mnView_OpenWnd.Checked = !mnView_OpenWnd.Checked;
				}
				else if (sender.Equals(mnView_Calc))
				{
					if (System.Diagnostics.Process.GetProcessesByName("Calc").Length == 0)
						System.Diagnostics.Process.Start("Calc.exe");

				}
				else if(sender.Equals(mnView_Chat))
				{
					string path = Directory.GetCurrentDirectory();
					path += "\\Chat\\Chat Masala.exe";
					if (System.Diagnostics.Process.GetProcessesByName("Chat Masala").Length == 0)
						System.Diagnostics.Process.Start(path);
				}
			}
			catch{}
		}

		private void menuWindows_Click(object sender, System.EventArgs e)
		{
			try
			{
				if (sender.Equals(mnWnd_Cascade))
					this.LayoutMdi(MdiLayout.Cascade);
				else 
					if (sender.Equals(mnWnd_Horiz))
					this.LayoutMdi(MdiLayout.TileHorizontal);
				else 
					if (sender.Equals(mnWnd_Vert))
					this.LayoutMdi(MdiLayout.TileVertical);
				else 
					if (sender.Equals(mnWnd_CloseAll))
				{
					foreach(BaseForm frm in this.MdiChildren)
						frm.Close();
				}
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message, " Thông báo !");
			}
		}
		private void menuHelp_Click(object sender, System.EventArgs e)
		{		
			try
			{
				if (sender.Equals(mnHelp_About))
				{
					FormAbout frmAbout = new FormAbout();
					frmAbout.ShowDialog(this);

				}
			}
			catch{}
		}

		private void menuSystem_Click(object sender, EventArgs e)
		{
			try
			{
				if (sender.Equals(mnSys_Exit))
				{
					if (isLogin)
					{
						DialogResult dlg = MessageBox.Show(getUICode(UICodes.ExitAppMgs), getUICode(UICodes.MgsBoxCaption), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
						if (DialogResult.Yes.Equals(dlg))
						{
							foreach(BaseForm frm in this.MdiChildren)
							{
								if (!frm.FormMode.Equals(FormModes.ViewMode))// && frm.GetType().Equals(typeof(BaseDataForm)))
								{
									DialogResult dlg1 = MessageBox.Show(getUICode(UICodes.CloseFormMgs), getUICode(UICodes.MgsBoxCaption), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
									if (DialogResult.Yes.Equals(dlg))
										frm.OnSaveData();
								}
								frm.Close();
							}
							this.Close();
						}
					}
					else
						this.Close();
				}
				else if (sender.Equals(mnSys_LockSys))
				{
                    FormLockSys frm = new FormLockSys(AulacClientGlobalMember.GlobalMember.UserName, AulacClientGlobalMember.GlobalMember.UserPassword);
					frm.Size = this.Size;
					frm.ShowDialog(this);
				}
				else if (sender.Equals(mnSys_Login))
				{
					FormLogin frmLogin = new FormLogin(this);
					frmLogin.ShowDialog();
					//ConnectSQL();
				}
				else if (sender.Equals(mnSys_Logout))
				{
					logout();
					setLogInOut(false);
				}
				if (sender.Equals(mnSys_ChangePass) )
				{
                    FormChangePW frmPass = new FormChangePW(this, AulacClientGlobalMember.GlobalMember.UserName, AulacClientGlobalMember.GlobalMember.UserPassword);
					frmPass.ShowDialog(this);
				}
				if (sender.Equals(mnSystem_Option))
				{
					FormOption frmOption= new FormOption(this);
					if (frmOption.ShowDialog(this).Equals(DialogResult.OK))
					{
						MessageBox.Show("Bạn phải đăng xuất rồi đăng nhập lại mới có tác dụng!!!\n Chương trình tự đăng xuất ngay bây giờ");
						logout();
						setLogInOut(false);
					}
				}
				if (sender.Equals(mnSystem_Company))
				{
                    ShowForm(typeof(FormCompanyInfo), true);
				}
				if (sender.Equals(mnSystem_User))
				{
                    ShowForm(typeof(FormUserMngt));
				}
				if (sender.Equals(mnSystem_UserGrp))
				{
                    ShowForm(typeof(FormListUserGrp));
				}
				if (sender.Equals(mnSystem_UserTasks))
				{
                    ShowForm(typeof(FormTasks), true);
				}
				if (sender.Equals(mnSys_ResetUser))
				{
                    ShowForm(typeof(FormResetUser), true);
				}
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}
		private void timerStatus_Tick(object sender, System.EventArgs e)
		{
			stPanelTime.Text = mServerDate.ToLongDateString() + "  " + mServerDate.ToShortTimeString();
		}

		#endregion 

		#region private methods
        private void SetListFormOpenning()
        {
            lvWnds1.ClearItem();
            foreach (Form frm in this.MdiChildren)
            {
                int i = lvWnds1.AddBlankItem();
                lvWnds1.setSubItem(i, colCaption, frm.Text);
                lvWnds1.setSubItem( i, colName, frm.Name);
            }
            if (frmBase == null || frmBase.IsDisposed)
                return;
            //lvWnds1.RowSelected = lvWnds1.FindIndex(1, frmBase.Name);
        }
       
        void frmBase_FormClosing(object sender, FormClosingEventArgs e)
        {
            lvWnds1.remove(lvWnds1.RowSelected);
        }
       
        private void InitOption() 
		{
            Options SysOption = null;
			try
			{
				XmlDataDocument doc = createXmlDocument(HMConfig.GetSystemOption, NounTypes.SystemInfo);
				doc  = processRequest(doc);
				XmlElement node = XmlProcess.GetVchHeaderElm(doc);
				SysOption = new Options(node);
			}
			catch
			{
				SysOption = new Options();
			}

			/*if (SysOption.IsCommaSeperate)
			{
				SystemCulture.NumberFormat.NumberDecimalSeparator = ",";
				SystemCulture.NumberFormat.NumberGroupSeparator = ".";
			}
			else
			{
				SystemCulture.NumberFormat.NumberDecimalSeparator = ".";
				SystemCulture.NumberFormat.NumberGroupSeparator = ",";
			}*/
			
			AuLacGlobalsBase.DateFormats dFormat = SysOption.DateFormat;

            System.Globalization.CultureInfo l_CultureInfo = AuLacGlobalsBase.DateTimeHelper.DateTimeFormat.CreateCultureInfo(SysOption.DateFormat);
            /*if (!SysOption.IsDayMonth)
			    l_CultureInfo =  new System.Globalization.CultureInfo("en-US");
            else
                l_CultureInfo = new System.Globalization.CultureInfo("vi-VN");
            */
			l_CultureInfo.NumberFormat.NumberDecimalSeparator = SysOption.IsCommaSeperate? "," : "." ;
            l_CultureInfo.NumberFormat.NumberGroupSeparator = SysOption.IsCommaSeperate ? "." : ","; 
			l_CultureInfo.NumberFormat.NumberDecimalDigits = SysOption.DecimalRound;
            l_CultureInfo.DateTimeFormat.ShortDatePattern = (SysOption.IsDayMonth) ? AuLacGlobalsBase.DateTimeHelper.DateTimeFormat.dd_MM_yyyy : AuLacGlobalsBase.DateTimeHelper.DateTimeFormat.MM_dd_yyyy;
            l_CultureInfo.DateTimeFormat.ShortTimePattern = AuLacGlobalsBase.DateTimeHelper.DateTimeFormat.HH_mm_ss; 
			Thread.CurrentThread.CurrentCulture = l_CultureInfo;
			//SystemCulture = l_CultureInfo;
            AulacClientGlobalMember.GlobalMember.SysOption = SysOption;
            AulacClientGlobalMember.GlobalMember.CultureInfo = l_CultureInfo;
           

			/*try
			{
				string path = Directory.GetCurrentDirectory();
				path += "\\Resource";
				if (!Directory.Exists(path))
					Directory.CreateDirectory(path);
				string xslPath = path + "\\XslFiles";
				if (!Directory.Exists(xslPath))
					Directory.CreateDirectory(xslPath);

				xslPath += "\\" + "Functions.xsl";
				System.IO.StreamReader rd = new System.IO.StreamReader(xslPath);				
				string str = rd.ReadToEnd();
				rd.Close();

				str = SetRptFormatNumber(str);
				System.IO.StreamWriter rw = new System.IO.StreamWriter(xslPath);
				rw.Write(str);
				rw.Close();
			}
			catch
			{
			}*/
		}
		
		string SetRptFormatNumber(string str)
		{
			Options op = AulacClientGlobalMember.GlobalMember.SysOption;

			int nFrom = str.IndexOf("select='format-number(") + "select='format-number(".Length;
			int nTo = str.IndexOf(", \"formatNumber\")'", nFrom);
			string oldFormat = str.Substring(nFrom, nTo-nFrom);

			string newFormat = "###_d_###_c_0";
			if (op.DecimalRoundReport>0)
			{
				for (int i=1; i<op.DecimalRoundReport; i++)
					newFormat += "#";
			}

			newFormat += ";(" + newFormat + ")"; 
			//newFormat = "###_d_###_c_0#;(###_d_###_c_0#)";

			if (op.IsCommaSeperate)
			{
				str = str.Replace("decimal-separator=\".\"", "decimal-separator=\",\"");
				str = str.Replace("grouping-separator=\",\"", "grouping-separator=\".\"");
				newFormat = newFormat.Replace("_d_", ".");
				newFormat = newFormat.Replace("_c_", ",");
			}
			else
			{
				str = str.Replace("decimal-separator=\",\"", "decimal-separator=\".\"");
				str = str.Replace("grouping-separator=\".\"", "grouping-separator=\",\"");
				newFormat = newFormat.Replace("_d_", ",");
				newFormat = newFormat.Replace("_c_", ".");
			}
			if (op.DecimalRoundReport!=0)
			{
				newFormat = "$xnum, \"" + newFormat + "\"";
			}
			else
			{
				string nTmp = "1";
				for (int i=0; i<op.RoundNumReport; i++)
					nTmp += "0";
				string sTmp = string.Format("round({0} div {1})*{2}, ", "$xnum", nTmp, nTmp);
				//string sTmp = string.Format("round({0} div {1})*{2} + round(({3} mod {4}) div {5})*{6}, ", "$xnum", nTmp, nTmp, "$xnum", nTmp, nTmp, nTmp );
				newFormat = sTmp + "\"" + newFormat.Replace("0", "#") + "\"";
			}

			str = str.Replace(oldFormat, newFormat);
			return str;
		}

		public void InitCompany() 
		{
			try
			{
				XmlDataDocument doc = createXmlDocument(HMConfig.GetCompanyInfo, NounTypes.SystemInfo);
				xmlCompanyInfo = processRequest(doc);
                XmlElement eL = XmlProcess.GetDataAreaElm(xmlCompanyInfo);

				/*string tmpComp = UICode.decodeString(XmlProcessor.getAttributeValue(node, tagCompany.Company));
				((XmlElement)node).SetAttribute(tagCompany.Company, tmpComp);
                 */
                this.Text = "Hệ thống quản lý viện phí " + eL.GetAttribute(tagCompany.Company) ;
			}
			catch
			{
				this.Text = "Hệ thống quản lý viện phí ";
			}
		}

		private void InitData()
		{
			processRequest(createXmlDocument(HMConfig.InitData, NounTypes.HspMngt));
		}
		#endregion
		
		#region asynchronous delegte
		public delegate void MyAsyncRepresenter();

		public void RunTwoProcs()
		{
			// instance of delegate for method we want to invoke
			MyAsyncRepresenter myDel = new MyAsyncRepresenter(MyAsynchronousProcess);

			// call the method asynchronously
			//Params:
			//1 - input param to MyAsynchrounousProcess method
			//2 - method called when MyAsynchronousProcess completes
			//3 - AsyncState for any purpose you need
			//I implemented it to hold the same param passed to method
			myDel.BeginInvoke(null, new AsyncCallback(MyAsyncProcCallback));

			// this represents the processing you want to do while the other call is working
			/*if (isEmpty(frmAbout))
				frmAbout = new FormAbout();
			frmAbout.ControlBox = false;
			frmAbout.ShowDialog(this);
			*/
		}

		// this is the separate thread you want to invoke
		public void MyAsynchronousProcess()
		{
			//initData();
			//frmAbout.ControlBox = true;
			//frmAbout.Close();
		}

		// when the separate thread completes
		//this is the method that will be called
		//so you can get the results and process them
		// You may put the results in a class field
		//for use by other routines 

		public void MyAsyncProcCallback(IAsyncResult ar)
		{
			// get the user defined object
			//- last param of BeginInvoke call
			bool myParam = (bool)ar.AsyncState;

			// AsyncResult object hold result info
			AsyncResult aResult = (AsyncResult)ar;

			// create a new instance of the original delegate type
			//that was used in the BeginInvoke
			//MyAsyncRepresenter temp = (MyAsyncRepresenter)aResult.AsyncRepresenter;

			// call EndInvoke, using the same IAsyncResult object (ar)
			//that was returned by the Asynchronous call to BeginInvoke
			//'ar' is what keeps BeginInvoke and EndInvoke in sync.
			//temp.EndInvoke(ar);

			// indicate that method has completed and the results
		}

		#endregion

		#region NotifyIcon
		private void setNotifyIcon()
		{
			try
			{
				MenuItem[] mnuItems = new MenuItem[4];
		
				//create the menu items array
				mnuItems[0] = new MenuItem("Kích hoạt", new EventHandler(this._Activate));
				mnuItems[0].DefaultItem = true;
				mnuItems[1] = new MenuItem("Trợ giúp", new EventHandler(this._Help));
				mnuItems[2] = new MenuItem("-");
				mnuItems[3] = new MenuItem("Đóng chương trình", new EventHandler(this._Exit));

				ContextMenu ctmnNotifyIcon = new ContextMenu(mnuItems);
			}
			catch{}
		}

		private void _Activate(object sender, System.EventArgs e)
		{
			if (this.WindowState.Equals(FormWindowState.Minimized)) 
			{
				this.Activate();
				this.Show();
				this.WindowState = FormWindowState.Maximized;
				//				MyIcon.Visible = false;
			}
		}

		private void _Help(object sender, System.EventArgs e)
		{
		}

		private void _Exit(object sender, System.EventArgs e)
		{
			try
			{
				if (isLogin)
				{
					DialogResult dlg = MessageBox.Show(getUICode(UICodes.ExitAppMgs), getUICode(UICodes.MgsBoxCaption), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
					if (DialogResult.Yes.Equals(dlg))
					{
						foreach(BaseForm frm in this.MdiChildren)
						{
							if (!frm.FormMode.Equals(FormModes.ViewMode))// && frm.GetType().Equals(typeof(BaseDataForm)))
							{
								DialogResult dlg1 = MessageBox.Show(getUICode(UICodes.CloseFormMgs), getUICode(UICodes.MgsBoxCaption), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
								if (DialogResult.Yes.Equals(dlg))
									frm.OnSaveData();
							}
							frm.Close();
						}
						this.Close();
					}
				}
				else
					this.Close();
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message, " Thông báo !");
			}
		}
		#endregion

		#region Menu listener
		private void Menu_SysDBMngt_Click(object sender, System.EventArgs e)
		{		
			try
			{
				if (sender.Equals(mnSysDB_New))
					ShowForm(typeof(FormCreateDatabase), true);
				if (sender.Equals(mnSysDB_Open))
				{
					if (this.isLogin)
					{
						if (MessageBox.Show("Hệ thống sẽ đóng cớ sở dữ liệu hiện tại bạn đang thao tác!\n\n\tBạn có muốn tiếp tục mở cơ sở dữ liệu mới(Y/N)?", " thông báo!", MessageBoxButtons.YesNo).Equals(DialogResult.Yes))
							setLogInOut(false);
						else
							return;
					}
					ConnectSQL();
				}
				if (sender.Equals(mnSysDB_Backup))
					ShowForm(typeof(FormBackup), true);
				if (sender.Equals(mnSysDB_Restore))
					ShowForm(typeof(FormRestore), true);

			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message, " Thông báo !");
			}
		}

		private void MainButton_Click(object sender, System.EventArgs e)
		{
			try
			{
			/*	foreach(Button bt1 in pnMainBt.Controls)
				{
					bt1.FlatStyle = FlatStyle.Popup;
					bt1.BackColor = SystemColors.ControlLight;
				}

				Button bt = (Button)sender;
				bt.FlatStyle = FlatStyle.Flat;
				bt.BackColor = SystemColors.Info;

				if (sender.Equals(btList))
					pnList.BringToFront();			
				else if (sender.Equals(btExamine))
					pnExamine.BringToFront();
				else if (sender.Equals(btHFee))
					pnHFee.BringToFront();
				else if (sender.Equals(btReport))
					pnReport.BringToFront();
				else if (sender.Equals(btSys))
					pnSystem.BringToFront();
				else if (sender.Equals(btMedicine))
					pnDrugMngt.BringToFront();
					*/
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message, " Thông báo !");
			}
		}


		private void List_Click(object sender, System.EventArgs e)
		{		
			try
			{
				if (sender.Equals(mnList_PsnType))
					ShowForm(typeof(FormEmplTypes));
				if (sender.Equals(mnList_Employee))
					ShowForm(typeof(FormEmployee));
				else if (sender.Equals(mnList_TreatyDept))
					ShowForm(typeof(FormTreatyDept));
				else if (sender.Equals(mnList_ReduceObj))
					ShowForm(typeof(FormReducedObject));
				else if (sender.Equals(mnList_HospitalFee))
                    ShowForm(typeof(FormListItemFees));
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void List_Medicine_Click(object sender, System.EventArgs e)
		{
			try
			{
				if (sender.Equals(mnList_Medicine))
					ShowForm(typeof(FormListDrugItems));
				else if (sender.Equals(mnList_MedicineGrp))
					ShowForm(typeof(FormDrugGrp));
                else if (sender.Equals(mnList_ChangeGrpItem))
                    ShowForm(typeof(FormChangeGrpItems));
				else if (sender.Equals(mnList_MediDrugStore))
					ShowForm(typeof(FormDrugStore));
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void Examine_Click(object sender, System.EventArgs e)
		{
			try
			{
                if (sender.Equals(mnOutsideExam_RegisOutsideExam))
					ShowForm(typeof(FormRegisExam));

                else if (sender.Equals(mnExamine_ListExamine))
                {
                    //ShowForm(typeof(FormListPntInHsp));
                }
                else if (sender.Equals(mnOutsideExam_OutsideExam))
                    ShowForm(typeof(FormPntOutsideExam));

			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void MedicineMngt_Click(object sender, System.EventArgs e)
		{
			try
			{
                if (sender.Equals(mnMedicine_IssueDept))
                {
                    //ShowForm(typeof(FormMdnDrugPntInDept));
                }
                else if (sender.Equals(mnMedicine_MdnTranferStore))
                    ShowForm(typeof(FormTranfeMdnStore));

                else if (sender.Equals(mnMedicine_Recv))
                    ShowForm(typeof(FormRecvMdnStore));
                else if (sender.Equals(mnMedicine_Rels))
                    ShowForm(typeof(FormRelsMedicine));
				

			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}
		
        private void Report_Click(object sender, System.EventArgs e)
		{		
			try
			{
				if (sender.Equals(mnReport_1))
					ShowForm(typeof(FormListReportSummary));
				else if (sender.Equals(mnReport_2))
					ShowForm(typeof(FormListReportStore));
				else if (sender.Equals(mnReport_3))
					ShowForm(typeof(FormListReportFinancial));
				
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void HospitalFee_Click(object sender, System.EventArgs e)
		{		
			try
			{
				if (sender.Equals(mnHFee_1))
					ShowForm(typeof(HospitalUI.PaymentFees.FormPayment));
                else if(sender.Equals(mnListVFeeOfPnt))
                    ShowForm(typeof(FormListVoucherFeeOfPnts));
                else if (sender.Equals(mnListFeeOfPnt))
                    ShowForm(typeof(FormListFeeOfPnt));
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}
		#endregion

		private void ctMnDrug_Scn_Click(object sender, System.EventArgs e)
		{
			if (sender.Equals(ctMnDrug_Scn)||sender.Equals(ctMnDrug_Scn))
					ShowForm(typeof(FormDrugScience));
				else if (sender.Equals(ctMnDrug_PatentMdn)||sender.Equals(ctMnDrug_PatentMdn))
					ShowForm(typeof(FormDrug));
		}
		
        private void menuItem1_Click(object sender, System.EventArgs e)
		{
			Form1 frm1 = new Form1();
			frm1.Show();
		}
       
        private void lvWnds_Click(object sender, EventArgs e)
        {
            frmBase = (BaseForm)this.MdiChildren.GetValue(lvWnds1.RowSelected);
            frmBase.Activate();
            lvWnds1.RowSelected = lvWnds1.FindIndex(1, frmBase.Name);
        }
       
        private void mnPerformSeviceCure_Click(object sender, EventArgs e)
        {
            if (sender.Equals(mnPerformSeviceCLS))
            {
                ShowForm(typeof(PerformCureForms.FormPeformCLS));
            }
        }


        #region IFormMainApp Members

        public void SetValueStatus(string pStatusText)
        {

            StatusText = pStatusText;
        }

        public string GetValueStatus()
        {
            return StatusText;
        }

        public void SetCursorForm(Cursor pCursor)
        {
            this.Cursor = pCursor;
        }


  
        #endregion
    }
	
}